package com.novel.utils;

import com.novel.pojo.system.SysLog;
import com.novel.pojo.system.User;
import com.novel.service.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;


@Aspect
@Configuration
public class AspectLogUtil {

    @Autowired
    private SysLogService logService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpSession session;

    /**
     * 设置切点
     */
    @Pointcut("execution(* com.novel.controller.*.*.*(..))")
    public void pt() {
    }

    /**
     * 环绕通知
     * AOP增强控制器,添加操作日志
     */
    @Around("pt()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        SysLog log = new SysLog();
        try {
            log.setId(UUID.randomUUID().toString());
            //获取用户信息
            Object object = session.getAttribute("loginUser");
            if (Objects.nonNull(object)) {
                User user = (User) object;
                //保存用户信息到log中
                log.setUserId(user.getUserId());
            }
            //设置请求ip
            log.setUserIp(ParseRealIpUtils.parseRealIpAddress(request));
            //设置时间
            log.setTime(new Date());
            //记录调用的方法签名
            log.setMethod(proceedingJoinPoint.getSignature().getName());
            //记录是那个控制器的方法
            log.setAction(proceedingJoinPoint.getTarget().getClass().getName());
            //设置
            log.setSuccess(1);
            return proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            log.setSuccess(0);
            throw throwable;
        } finally {
            //保存日志信息
            logService.insertSystemSysLog(log);
        }
    }

}